trigger OrderTrigger on Order__c (before insert, after update) {
	try{
	if(Trigger.isBefore && Trigger.isInsert)
	{
		List<Order__c> orders = Trigger.new;
		List<Item_Group_Approver__c> itemGpApprs = [SELECT id,name,Item_Group__c, User__c From Item_Group_Approver__c LIMIT 50000];
		Map<ID,List<ID>> itemApproverMap = new Map<ID,List<ID>>();
		if(itemGpApprs!=NULL)
		{
			List<Id> appList;
			for(Item_Group_Approver__c itmgrpAppr : itemGpApprs)
			{
				if(itemApproverMap.containsKey(itmgrpAppr.Item_Group__c))
				{
				    itemApproverMap.get(itmgrpAppr.Item_Group__c).add(itmgrpAppr.User__c);
				}
				else
				{
				    appList = new List<Id>();
				    appList.add(itmgrpAppr.User__c);
				    itemApproverMap.put(itmgrpAppr.Item_Group__c,appList);
				}
			}
		}
		
		for(Order__c ord : orders)
		{
			List<Id> ApproverIds = itemApproverMap.get(ord.Item_Group__c);
			
			ord.User__c = ApproverIds[0];
			ord.Approver2__c = ApproverIds[1];
		}
	}
	
	if(Trigger.isAfter && Trigger.isUpdate)
	{
		Map<Id,Item_Group__c> ItemGroupMap = new Map<Id,Item_Group__c>();
		Map<Id,User> UserMap = new Map<Id,User>();
		List<User> users = [SELECT id,Name,Email FROM User LIMIT 50000];
		List<Item_Group__c> ItemGroupsTemp = new List<Item_Group__c>();
		Item_Group__c TempItemGroup;
		List<Item_Group__c> ItemGroups = [SELECT id,Name,Total_Inventory__c From Item_Group__c LIMIT 50000];
		if(ItemGroups!=null)
		{
			for(Item_Group__c itemGroup : ItemGroups)
			{
				ItemGroupMap.put(itemGroup.id,itemGroup);		
			}
		}
		if(Users!=null)
		{
		  for(User usr : Users)
		  {
		      UserMap.put(usr.id,usr);
		  }
		}
		for(Order__c prevOrder : Trigger.old)
		{	
			for(Order__c newOrder : Trigger.new)
			{
				if(prevOrder.Status__c=='Pending' && newOrder.Status__c=='Approved')
				{
					TempItemGroup = new Item_Group__c();
					TempItemGroup = ItemGroupMap.get(newOrder.Item_Group__c);
					
					Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(new String[] {UserMap.get(newOrder.createdById).Email});
                    mail.setSubject('Order Approved');
                    mail.setPlainTextBody('Your oder '+newOrder.Name+' Has approved. Add Items to the inventory');
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ mail });
				}
			}
		}
		if(TempItemGroup != null)
		{
			update TempItemGroup;
		}
	}
	}
	catch(Exception ex)
	{
	   System.debug(ex);
	   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Data Insertion Failed');
       ApexPages.addMessage(myMsg); 
	}
}